import { createRouter, createWebHashHistory } from 'vue-router'
import { getToken } from '@/utils/auth' // get token from cookie
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

import { constantRoutes, dynamicRoutes, constantTailRoutes } from './routes'

export const wholeRoutes = constantRoutes.concat(dynamicRoutes);


// syncRoutesComponent(constantRoutes, dynamicRoutes)


const router = createRouter({
  history: createWebHashHistory(),
  /**
   * 说明：
   * 1、notFoundAndNoPower 默认添加 404、401 界面，防止一直提示 No match found for location with path 'xxx'
   * 2、backEnd.ts(后端控制路由)、frontEnd.ts(前端控制路由) 中也需要加 notFoundAndNoPower 404、401 界面。
   *    防止 404、401 不在 layout 布局中，不设置的话，404、401 界面将全屏显示
   */
  routes: constantRoutes.concat(constantTailRoutes),
})


router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  if (to.matched.length == 0) {
    if(from.path === '/welcome') {
      next({ path: '/404' })
    }else {
      // const raw: LocationAsRelativeRaw = { name: 'welcome', params: { from: from.path } }
      // next(`/welcome?redirect=${to.path}`)
      next({ path: '/welcome', query: { redirect: to.path } })
    }
    NProgress.done()
  } else {
    // determine whether the user has logged in
    const hasToken = getToken()

    if (hasToken) {
      if (to.path === '/login') {
        // if is logged in, redirect to the home page
        next({ path: '/' })
        NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
      } else {
        next()
        NProgress.done()
      }
    } else {
      /* has no token*/

      if (whiteList.indexOf(to.path) !== -1) {
        // in the free login whitelist, go directly
        next()
        NProgress.done()
      } else {
        // other pages that do not have permission to access are redirected to the login page.
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }



})



export default router
